/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
 */

package com.jinhe.tss.component.support.web.webwork;

import java.util.Date;
import java.util.Map;

import ognl.DefaultTypeConverter;

import com.jinhe.tss.core.util.DateUtil;

/** 
 * <p> DateConverter.java </p> 
 * 
 * 日期转换 现在默认的日期格式为：yyyy-MM-dd
 * 
 */
public class DateConverter extends DefaultTypeConverter {

    @SuppressWarnings("unchecked")
	public Object convertValue(Map ognlContext, Object value, Class toType) {
		Object result = null;
		
		if (toType == Date.class) {
			result = doConvertToDate(value);
		} 
		
		if (toType == String.class) {
			if (value instanceof Date) {
	            result = DateUtil.format((Date)value);
	        }
		}
		
		return result;
	}

	private Date doConvertToDate(Object value) {
		Date result = null;

		if (value instanceof String) {
		    return DateUtil.parse((String)value);
		}
		else if (value instanceof Object[]) {
			// let's try to convert the first element only
			Object[] array = (Object[]) value;
			if ((array != null) && (array.length >= 1)) {
				value = array[0];
				result = doConvertToDate(value);
			}
		} else if (Date.class.isAssignableFrom(value.getClass())) {
			result = (Date) value;
		}
		return result;
	}
 
}
